/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package API;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
import entities.Article;
import java.io.*;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

/**
 *
 * @author remi
 */
@Stateless
@Path("/article")
public class ArticleFacadeREST extends AbstractFacade<Article> {
    @PersistenceContext(unitName = "BlogWSPU")
    private EntityManager em;

    public ArticleFacadeREST() {
        super(Article.class);
    }

    @POST
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public String create(@FormDataParam("titre") String titre,
                         @FormDataParam("content") String content,
                         @FormDataParam("image0") InputStream uploadedInputStream,
                         @FormDataParam("image0") FormDataContentDisposition fileDetail) throws IOException
    {
        System.out.println("Titre : "+titre+"\ncontent : "+content+"\nStream"+uploadedInputStream+"\nDetail"+fileDetail);
        //Create directory
        try{
            String strDirectoy = "images";
            boolean success = (new File(strDirectoy)).mkdir();
            if (success) {
                 System.out.println("Directory: "
                  + strDirectoy + " created");
            }else{
                System.out.println("Le dossier existe déjà :");
            }
            }catch(Exception e){
                System.err.println("Error: " + e.getMessage());
            }
        
        //Save file
        try{
            File f = new File("D:/"+fileDetail.getFileName());
            OutputStream out=new FileOutputStream(f);
            byte buf[]=new byte[1024];
            int len;
            while((len=uploadedInputStream.read(buf))>0)
                out.write(buf,0,len);
            out.close();
            uploadedInputStream.close();
        }catch(FileNotFoundException e){
            System.out.println("Error funtion create / creating file\n");
            e.printStackTrace();
        }catch(IOException e){
            System.out.println("Error IOE\n");
            e.printStackTrace();
        }
        
        //Article creation
        Article a = new Article(titre,content);
        a.setImage("D:/"+fileDetail.getFileName());
        super.create(a);
        return "/BlogWS_Version_Test/resources/article/";
    }

    @PUT
    @Consumes({MediaType.APPLICATION_FORM_URLENCODED, "application/json"})
    public Article edit(MultivaluedMap<String, String> inFormParams) {
        Article a = super.find(Long.parseLong(inFormParams.getFirst("id")));
        a.setContent(inFormParams.getFirst("content"));
        a.setTitre(inFormParams.getFirst("titre"));
        super.edit(a);
        return a;
    }

    @DELETE
    @Path("{id}")
    public String remove(@PathParam("id") Long id) {
        super.remove(super.find(id));
        return ""+id;
    }

    @GET
    @Path("{id}")
    @Produces({"application/json"})
    public Article find(@PathParam("id") Long id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({"application/json"})
    public List<Article> findAll() {
        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({"application/xml", "application/json"})
    public List<Article> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        int[] range = new int[]{from, to};
        Query q = em.createQuery("select a from Article a ORDER BY a.time ASC", Article.class);
        q.setMaxResults(range[1]-range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    
    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }

    @java.lang.Override
    protected EntityManager getEntityManager() {
        return em;
    }
}
